<script setup lang="ts">
  import { computed, ref, onMounted, nextTick } from 'vue'
  import { Sender } from 'vue-element-plus-x'
  import { PLACEHOLDER } from '../utils/constant'
  import { NUpload, NTooltip, NEllipsis, useMessage, NIcon } from 'naive-ui'
  import SvgIcon from '@/components/SvgIcon/index.vue'
  import { getPreset } from '@/api/agent'
  import { uploadFile } from '@/api/common'
  import { CloseOutlined } from '@vicons/material'
  import { fileSizeConversion } from '@/utils/functions'
  const props = defineProps<{
    curAgent: string
    isDefault: boolean
    isSending: boolean
  }>()

  const disabled = computed(() => {
    return content.value.trim().length === 0 || props.isSending
  })
  const fileList = ref<any[]>([])
  const content = ref('')
  const inputStyle = {
    color: '#000',
    height: '22px',
    fontSize: '16px',
    fontWeight: '500',
    lineHeight: '22px',
    fontFamily: 'PingFang SC',
  }
  const emit = defineEmits(['send'])
  const handleSend = () => {
    if (disabled.value) return
    emit('send', content.value, fileList.value)
    fileList.value = []
    content.value = ''
  }

  const showCommonPhrases = ref(false)
  const onTrigger = (value: { newValue: string; oldValue: string }) => {
    const { newValue } = value
    if (newValue.includes('/') && !showCommonPhrases.value) {
      showCommonPhrases.value = true
    }
  }

  const handleCommonPhrases = (item: any) => {
    content.value = item.content
    showCommonPhrases.value = false
  }

  const presetList = ref<any[]>([])
  const getPresetFn = async () => {
    const res = await getPreset()
    presetList.value = res
  }

  const height = computed(() => {
    // 计算高度
    return (
      120 +
      (showCommonPhrases.value ? presetList.value.length * 40 : 0) +
      (fileList.value.length > 0 ? 69 : 0)
    )
  })

  const message = useMessage()
  const handleBeforeUpload = async ({ file }: any) => {
    // 验证文件类型
    const allowedTypes = [
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/pdf',
      'text/plain',
      'text/markdown',
    ]
    if (!allowedTypes.includes(file.file.type) && !file.file.name.toLowerCase().endsWith('.md')) {
      message.error('只支持 .doc, .docx, .pdf, .txt, .md 格式的文件')
      return false // 阻止上传
    }
    const formData = new FormData()
    formData.append('file', file.file)
    formData.append('type', '1') // 普通上传文件存储
    const res = await uploadFile(formData)
    fileList.value.push(res)
    await nextTick(() => {
      senderRef.value.openHeader()
    })
    return true
  }

  const senderRef = ref()
  onMounted(async () => {
    await getPresetFn()
    senderRef.value.openHeader()
  })

  const handleCloseFile = () => {
    fileList.value = []
  }

  const handleClear = () => {
    fileList.value = []
    content.value = ''
  }

  defineExpose({
    height,
    handleClear,
  })
</script>

<template>
  <div>
    <div
      class="mb-2 w-[900px] mx-auto"
      v-show="showCommonPhrases && !props.isDefault"
      @mouseleave="showCommonPhrases = false"
    >
      <div
        v-for="item in presetList"
        :key="item.id"
        @click="handleCommonPhrases(item)"
        class="w-full h-10 leading-10 text-[#000000] flex items-center cursor-pointer hover:bg-[#F6F6F6] rounded px-4"
      >
        <n-ellipsis>
          <SvgIcon name="common-phares" class="text-[14px] mr-1 align-middle" />
          <span class="text-[14px]">{{ item.content }}</span>
        </n-ellipsis>
      </div>
    </div>
    <Sender
      ref="senderRef"
      @submit="handleSend"
      variant="updown"
      :placeholder="PLACEHOLDER"
      v-model="content"
      :inputStyle="inputStyle"
      :auto-size="{ minRows: 2, maxRows: 2 }"
      class="w-[900px] sender-container mx-auto mt-6"
      :trigger-strings="['/']"
      @trigger="onTrigger"
    >
      <!-- 顶部文件 -->
      <template #header v-if="fileList.length > 0">
        <div class="flex justify-between px-2 py-1 h-[45px] max-w-[200px] bg-[#F0F4F9] rounded-lg">
          <div class="w-[calc(100%-24px)]">
            <n-ellipsis>
              <span class="leading-[18px] text-[12px] font-bold">{{ fileList[0].fileName }}</span>
            </n-ellipsis>
            <div class="flex items-center gap-1">
              <div class="text-[#666D7A] text-[8px] font-bold">
                {{ fileSizeConversion(fileList[0].fileSize) }}
              </div>
            </div>
          </div>
          <n-icon>
            <CloseOutlined @click="handleCloseFile" class="text-[16px] cursor-pointer" />
          </n-icon>
        </div>
      </template>
      <!-- 操作列表 -->
      <template #action-list>
        <div class="h-[56px] flex items-center justify-between w-full">
          <n-upload
            :disabled="fileList.length > 0"
            accept=".doc,.docx,.pdf,.txt,.md"
            class="h-8 w-8"
            :on-before-upload="handleBeforeUpload"
            :show-file-list="false"
          >
            <n-tooltip placement="bottom">
              <template #trigger>
                <div
                  :class="{ '!cursor-not-allowed': fileList.length > 0 }"
                  class="rounded h-8 w-8 flex items-center justify-center cursor-pointer hover:bg-[#EFF1F5]"
                >
                  <SvgIcon name="upload-link" class="text-[32px]" />
                </div>
              </template>
              <span>添加文件</span>
            </n-tooltip>
          </n-upload>
          <div class="h-8 w-8 flex items-center justify-center cursor-pointer" @click="handleSend">
            <SvgIcon
              name="send"
              class="text-[32px] text-[#0B5CFF]"
              :class="{ 'text-[#C2D6FF] cursor-not-allowed': disabled }"
            />
          </div>
        </div>
      </template>
    </Sender>
    <div
      class="mt-2 w-[900px] mx-auto"
      v-show="showCommonPhrases && props.isDefault"
      @mouseleave="showCommonPhrases = false"
    >
      <div
        v-for="item in presetList"
        :key="item.id"
        @click="handleCommonPhrases(item)"
        class="w-full h-10 leading-10 text-[#000000] flex items-center cursor-pointer hover:bg-[#F6F6F6] rounded px-4"
      >
        <n-ellipsis>
          <SvgIcon name="common-phares" class="text-[14px] mr-1 align-middle" />
          <span class="text-[14px]">{{ item.content }}</span>
        </n-ellipsis>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .sender-container {
    cursor: pointer;

    :deep(.el-sender-action-list) {
      width: 100%;
    }

    :deep(.el-sender:focus-within) {
      border-color: #0b5cff !important;
    }

    :deep(.el-sender-content) {
      padding-block-start: 8px !important;
      padding-block-end: 0 !important;
      gap: 4px !important;
    }

    :deep(.el-textarea__inner) {
      &::placeholder {
        font-weight: 400;
      }
    }

    :deep(.el-sender-header) {
      padding-left: 16px;
      padding-top: 16px;
      padding-bottom: 8px;
      border-bottom: none !important;
    }
  }
</style>
